package middlewave

import (
	"backend/constants/errorCode"
	"backend/models"
	"backend/service/common"
	"backend/utils"
	"github.com/beego/beego/v2/server/web/context"
	"strings"
)

// CheckToken
// 通过token进行鉴权操作
func CheckToken(ctx *context.Context) {
	token := ctx.Input.Header("Token")
	//logs.Info("checkToken !!!")
	isExistToken := false
	if token != "" {
		isExistToken, _ = common.CheckToken(token)
	}
	if !isExistToken {
		result := errorCode.ErrTokenVerify
		str := utils.Strval(result)
		ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
		ctx.WriteString(str)
		return
	}else{
		var result interface{}
		flg := false
		username := common.GetUserId(ctx)
		access := models.GetUserAccessByUid(username)
		//logs.Info(access)
		if !access["list"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/list") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["read"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/read") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["write"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/write") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["copy"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/copy") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["rename"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/rename") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["create"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/create") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if !access["remove"].(bool)&& strings.Contains(ctx.Request.RequestURI,"/file/remove") {
			result = errorCode.ErrServer.SetMsg("权限不足")
			flg = true
		}
		if flg {
			str := utils.Strval(result)
			ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
			ctx.WriteString(str)
			return
		}
	}
}